<!-- 企业编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="1000"
    :model-value="modelValue"
    title="发工资"
    @update:modelValue="updateModelValue"
    resizable="vertical"
  >
    <div class="tools">
      <el-input
        clearable
        :maxlength="20"
        v-model="form.amount"
        placeholder=""
        style="width: 150px"
        class="input"
      >
        <template #prepend>工资</template>
      </el-input>

      <el-input
        clearable
        :maxlength="20"
        v-model="form.workingTime"
        style="width: 150px"
        class="input"
      >
        <template #prepend>工时</template>
      </el-input>

      <el-input
        clearable
        :maxlength="20"
        v-model="form.credit"
        style="width: 150px"
        class="input"
      >
        <template #prepend>积分</template>
      </el-input>

      <el-button type="warning" :loading="loading" @click="setSalary()">
        批量直接填写
      </el-button>
    </div>
    <div class="tools">
      <el-input
        clearable
        :maxlength="20"
        v-model="salaryInfo.workingTime"
        placeholder=""
        style="width: 150px"
        class="input"
      >
        <template #prepend>工时</template>
      </el-input>

      <el-input
        clearable
        :maxlength="20"
        v-model="salaryInfo.hourlyWage"
        style="width: 150px"
        placeholder="薪资"
        class="input"
      >
        <template #prepend>元</template>
      </el-input>

      <el-button type="warning" :loading="loading" @click="setWorkingTime()">
        批量直接填写
      </el-button>
    </div>
    <div class="tools">
      <el-switch
        v-model:model-value="hasCredit"
        active-text="有积分"
        inactive-text="无积分"
      />
    </div>

    <ele-pro-table
      ref="tableRef"
      :columns="columns"
      :datasource="datasource"
      :show-overflow-tooltip="true"
      highlight-current-row
      border
      stripe
      :pagination="false"
      :show-summary="true"
      :summary-method="getSummaries"
    >
      <template #toolbar>
        <span style="font-weight: bold">
          {{ job.company.company_name }} - {{ job.title }}【
          {{ job.salary }}
          {{ job.salary_unit }} 】
        </span>
      </template>
      <template #salary="{ row, $index }">
        <el-input
          v-model="row.amount"
          placeholder="金额"
          class="filter-item"
          oninput="value=value.replace(/[^0-9.]/g,'')"
          @input="count($index)"
        />
      </template>
      <template #workingTime="{ row, $index }">
        <el-input
          v-model="row.workingTime"
          placeholder="工时"
          class="filter-item"
          oninput="value=value.replace(/[^0-9.]/g,'')"
          @input="countSalary($index)"
        />
      </template>
      <template #credit="{ row }">
        <el-input
          v-model="row.credit"
          placeholder="积分"
          oninput="value=value.replace(/[^0-9.]/g,'')"
          class="filter-item"
        />
      </template>
      <template v-if="type === 'judge'" #action="{ row }">
        <el-button-group>
          <el-button
            v-if="row.id > 0"
            type="success"
            size="small"
            @click="pass(row)"
            >通过</el-button
          >
          <el-button
            v-if="row.id > 0"
            type="danger"
            size="small"
            @click="reject(row)"
            >拒绝</el-button
          >
        </el-button-group>
      </template>
    </ele-pro-table>
    <div class="foot">
      <el-button
        type="success"
        v-if="type === 'judge'"
        :loading="loading"
        @click="pass()"
      >
        全部通过审核
      </el-button>
      <el-button v-else type="success" :loading="loading" @click="save()">
        提交审核
      </el-button>
      <!-- <span>{{ total.user }}人 工资:{{ total.amount }}元</span> -->
    </div>
  </ele-modal>
</template>

<script setup>
  import { ref, watch, computed } from 'vue';
  import { ElMessageBox } from 'element-plus/es';
  import { EleMessage } from 'ele-admin-plus/es';
  import { pageApplyRecord, paySalary } from '@/api/company';
  import { pageJobSalary, payToAccount, rejectJobSalary } from '@/api/money';
  import { jsChengfa } from '@/utils/my-common';

  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    job: Object,
    type: String
  });

  /** 提交状态 */
  const loading = ref(false);

  /** 表格实例 */
  const tableRef = ref(null);

  /** 表单数据 */
  const form = ref({
    salary: '',
    workingTime: '',
    credit: ''
  });

  /** 批量计算填写用 */
  const salaryInfo = ref({
    hourlyWage: '',
    workingTime: ''
  });

  /** 统计用 */
  const total = ref({
    amount: 0, // 工资
    user: 0 // 人数
  });

  /** 表格列配置 */
  const columns = computed(() => {
    const cols = [
      {
        type: 'index',
        columnKey: 'index',
        width: 60,
        align: 'center'
      },
      {
        prop: 'realname',
        label: '名字',
        width: 85
      },
      {
        prop: 'tel',
        label: '电话',
        width: 122
      },

      {
        prop: 'paid',
        label: '已发',
        width: 85,
        align: 'center'
      }
    ];

    if (props.type !== 'judge') {
      cols.push({
        prop: 'wating_pay',
        label: '待审',
        width: 85,
        align: 'center'
      });
    }
    cols.push(
      {
        label: '工资',
        align: 'center',
        slot: 'salary'
      },
      {
        label: '结算工时',
        align: 'center',
        slot: 'workingTime'
      },
      {
        label: '积分',
        align: 'center',
        slot: 'credit'
      },
      {
        label: '操作',
        align: 'center',
        width: 130,
        slot: 'action'
      }
    );
    return cols;
  });

  /** 总计方法 */
  const sum = (data, prop) => {
    var total = 0;
    for (let i = 0; i < data.length; i++) {
      const element = data[i];
      total += element[prop] * 1;
    }
    return total;
  };
  const getSummaries = (param) => {
    const { columns, data } = param;
    const sums = [];
    const judge = props.type === 'judge';

    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '总计';
        return;
      }
      if (index === 3) sums[index] = sum(data, 'paid');

      if (index === 4)
        sums[index] = judge ? sum(data, 'amount') : sum(data, 'wating_pay');

      if (index === 5)
        sums[index] = judge ? sum(data, 'workingTime') : sum(data, 'amount');

      if (index === 6)
        sums[index] = judge ? sum(data, 'credit') : sum(data, 'workingTime');

      if (index === 7) sums[index] = judge ? '' : sum(data, 'credit');
    });

    return sums;
  };

  /** 表格数据源 */
  const datasource = ({ page, where, orders }) => {
    if (props.type === 'judge') {
      // 待审核工资
      return pageJobSalary({
        ...where,
        ...orders,
        page,
        limit: 99999999,
        cate: '正常',
        job_id: props.job.id,
        statistical: 0,
        status: 0,
        watingPay: 1
      });
    }
    // 报名记录 - 发工资
    return pageApplyRecord({
      ...where,
      ...orders,
      page,
      limit: 99999999,
      status: 1,
      accept: 1,
      id: props.job.id
    });
  };
  /** 搜索 */
  const reload = (where) => {
    tableRef.value?.reload?.({
      page: 1,
      where
    });
  };

  // 批量设置工资
  const setWorkingTime = () => {
    const list = tableRef.value.getData();
    var data = [];
    const amount = jsChengfa(
      salaryInfo.value.workingTime,
      salaryInfo.value.hourlyWage
    );
    for (let i = 0; i < list.length; i++) {
      var row = [];
      row = list[i];
      row.amount = amount;
      row.workingTime = salaryInfo.value.workingTime;
      data.push(row);
    }
    tableRef.value?.setData([...data]);
    this.count(99999999);
  };

  /** 批量填写工资 */
  const setSalary = () => {
    const list = tableRef.value.getData();
    var data = [];
    console.log(list);
    for (let i = 0; i < list.length; i++) {
      var row = [];
      row = list[i];
      row.amount = form.value.amount;
      row.workingTime = form.value.workingTime;
      row.credit = form.value.credit;
      data.push(row);
    }
    console.log(data);
    tableRef.value?.setData([...data]);
    // this.count(99999999);
  };

  /** 判断是否有积分，单独做那种才有 */
  const hasCredit = ref(true);

  // 统计总共发了多少工资
  const count = (index) => {
    console.log(hasCredit.value, '是否有积分');
    var amount = 0;

    var creditExc = hasCredit.value ? 0.003 : 0; // 积分兑换率
    console.log(creditExc, '积分汇率');
    const list = tableRef.value.getData();
    // var total = 0
    for (var i = 0; i < list.length; i++) {
      amount += list[i].amount * 100;
      var credit = list[i].amount * creditExc;
      if (index === 99999999) list[i].credit = credit;
      // total++
    }

    total.value.user = list.length;
    total.value.amount = amount / 100;

    credit = list[index].amount * creditExc;
    console.log(credit);
    // 单独设置 那积分最多只能到3
    if (index < 99999999) list[index].credit = credit > 3 ? 3 : credit;
  };

  // 根据输入的工时自动计算工资
  const countSalary = (index) => {
    const list = tableRef.value.getData();
    const time = list[index].workingTime;
    const money = salaryInfo.value.hourlyWage;
    if (money !== '' && money > 0) {
      list[index].amount = jsChengfa(time, salaryInfo.value.hourlyWage);
      count(index);
    }
    // console.log(this.salaryInfo.hourlyWage, time)
  };

  /** 拒绝 */
  const reject = (row) => {
    ElMessageBox.confirm(
      '确定拒绝“' + row.realname + '”的工资发放申请吗?',
      '系统提示',
      { type: 'warning', draggable: true }
    )
      .then(() => {
        const loading = EleMessage.loading('请求中..');
        rejectJobSalary({ id: row.id })
          .then(() => {
            EleMessage.success('操作成功!');
            loading.close();
            reload();
          })
          .catch(() => {
            loading.close();
          });
      })
      .catch(() => {});
  };

  /** 审核通过 */
  const pass = (row) => {
    var text = row
      ? '确定要通过“' + row.realname + '”的工资发放申请吗?'
      : '确定要通过所有的工资发放申请吗？';
    ElMessageBox.confirm(text, '系统提示', { type: 'warning', draggable: true })
      .then(() => {
        const loading = EleMessage.loading('请求中..');

        var requestData = [];
        if (row) {
          requestData.push(row);
        } else {
          var list = tableRef.value.getData();
          for (let i = 0; i < list.length; i++) {
            if (
              list[i]['status'] === 0 &&
              (list[i]['amount'] > 0 ||
                list[i]['amount_vip'] > 0 ||
                list[i]['amount_subsidy'] > 0 ||
                list[i]['credit'] > 0)
            ) {
              var v = {
                id: list[i].id,
                amount: list[i].amount,
                amount_vip: list[i].amount_vip,
                amount_subsidy: list[i].amount_subsidy,
                credit: list[i].credit,
                salary: list[i].salary,
                status: list[i].status,
                type: list[i].type,
                code: list[i].code,
                title: list[i].title,
                student_id: list[i].student_id,
                belongs_id: list[i].belongs_id,
                apply_record_id: list[i].apply_record_id,
                working_time: list[i].working_time,
                company_name: list[i].company_name,
                site_id: list[i].site_id
              };
              requestData.push(v);
            }
          }
        }

        requestData = JSON.stringify(requestData);

        payToAccount({ list: requestData, payType: '正常' })
          .then(() => {
            EleMessage.success('操作成功!');
            loading.close();
            reload();
          })
          .catch(() => {
            loading.close();
          });
      })
      .catch(() => {});
  };

  /** 发工资提交审核 */
  const save = () => {
    var list = tableRef.value.getData();
    var requestData = [];
    for (var i = 0; i < list.length; i++) {
      const v = {
        accept: list[i].accept,
        amount_vip: list[i].amount_vip,
        credit: list[i].credit,
        amount: list[i].amount,
        member_id: list[i].member_id,
        belongs_id: list[i].belongs_id,
        apply_record_id: list[i].id,
        amount_subsidy: list[i].amount_subsidy,
        salary: list[i].salary,
        working_time: list[i].workingTime ? list[i].workingTime : 0
      };
      requestData.push(v);
    }
    // console.log(this.acceptList)
    // var requestData = Object.assign({}, this.acceptList)
    requestData = JSON.stringify(requestData);

    paySalary({ list: requestData, payType: '正常', salaryType: '线上' })
      .then((msg) => {
        loading.value = false;
        EleMessage.success(msg);
        updateModelValue(false);
        emit('done');
      })
      .catch((e) => {
        loading.value = false;
        EleMessage.error(e.message);
      });
  };

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        console.log('wtf', props.job);
        form.value.amount = '';
        form.value.salary = '';
        form.value.workingTime = '';
        salaryInfo.value.workingTime = '';
        salaryInfo.value.hourlyWage = '';
        // credit.value = props.data.work_date_time > 0;
      }
    }
  );
</script>

<style scoped>
  .tools {
    display: flex;
    margin-bottom: 10px;
    .input {
      margin-right: 8px;
    }
  }
  .foot {
    margin-top: 10px;
    span {
      margin-left: 14px;
      font-size: 12px;
    }
  }
</style>
